﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using BCMS.Settings;
namespace BCMS.Forms
{
    public partial class frmSystemBackupAndRestore : Form
    {
        public string Action { set; get; }

        public frmSystemBackupAndRestore(string action)
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();
            Action = action;
        }

        private void frmBackupAndRestore_Load(object sender, EventArgs e)
        {
            switch (Action)
            {
                case "Backup":
                    this.Text = "[BCMS] - Sao lưu";
                    grpHelper.Text = "Đường dẫn đến file mysqldump.exe";
                    txtHelperPath.Text = Application.StartupPath + "\\Libs\\mysqldump.exe";
                    break;
                case "Restore":
                    this.Text = "[BCMS] - Khôi phục";
                    grpHelper.Text = "Đường dẫn đến file mysql.exe";
                    txtHelperPath.Text = Application.StartupPath + "\\Libs\\mysql.exe";
                    break;
                default:
                    this.Close();
                    break;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            switch (Action)
            {
                case "Backup":
                    SaveFileDialog dlg = new SaveFileDialog();
                    dlg.Filter = "Dump File|*.dmp|SQL File|*.sql";
                    dlg.Title = "Chọn file lưu";
                    dlg.InitialDirectory = Application.StartupPath;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        txtDataPath.Text = dlg.FileName;
                    } 
                    break;
                case "Restore":
                    OpenFileDialog oFile = new OpenFileDialog();
                    oFile.Filter = "Dump files|*.dump|SQL File|*.sql";
                    oFile.Title = "Chọn file dữ liệu gốc";
                    oFile.InitialDirectory = Application.StartupPath;
                    if (oFile.ShowDialog() == DialogResult.OK)
                        txtDataPath.Text = oFile.FileName;
                    break;
                default:
                    break;
            }
            
        }

        private void backup()
        {
            if (txtDataPath.Text.Trim() == "")
            {
                MessageBox.Show("Tệp sao lưu không hợp lệ.", "Cảnh báo");
                txtDataPath.Focus();
                return;
            }

            if (txtServer.Text.Trim() == "")
            {
                MessageBox.Show("Địa chỉ server cơ sở dữ liệu không hợp lệ.", "Cảnh báo");
                txtServer.Focus();
                return;
            }
            if (txtDBName.Text.Trim() == "")
            {
                MessageBox.Show("Tên cơ sở dữ liệu không hợp lệ.", "Cảnh báo");
                txtDBName.Focus();
                return;
            }
            if (txtUserName.Text.Trim() == "")
            {
                MessageBox.Show("Tên truy cập cơ sở dữ liệu không hợp lệ.", "Cảnh báo");
                txtUserName.Focus();
                return;
            }

            string result = BackupMySQLDatabase(txtDBName.Text.Trim(),
                txtHelperPath.Text, txtUserName.Text.Trim(),
                txtPassword.Text.Trim(), txtServer.Text.Trim(),
                txtDataPath.Text.Trim());

            if (result == "")
            {
                try
                {
                    FileInfo f = new FileInfo(txtDataPath.Text.Trim());
                    if (!f.Length.Equals(0))
                    {
                        GlobalVars.ShowInfo("Sao lưu cơ sở dữ liệu [THÀNH CÔNG]");
                        DialogResult = DialogResult.OK;
                    }
                    else
                        GlobalVars.ShowError("Lỗi sao lưu");

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show(result, "Cảnh báo");
            }
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            switch (Action)
            {
                case "Backup":
                    backup();
                    break;
                case "Restore":
                    restore();
                    break;
                default:
                    break;
            }
        }

        private void restore()
        {
            if (txtDataPath.Text.Trim() == "" || !File.Exists(txtDataPath.Text.Trim()))
            {
                MessageBox.Show("Tệp phục hồi không hợp lệ.", "Cảnh báo");
                txtDataPath.Focus();
                return;
            }

            if (txtServer.Text.Trim() == "")
            {
                MessageBox.Show("Địa chỉ server cơ sở dữ liệu không hợp lệ.", "Cảnh báo");
                txtServer.Focus();
                return;
            }
            if (txtDBName.Text.Trim() == "")
            {
                MessageBox.Show("Tên cơ sở dữ liệu không hợp lệ.", "Cảnh báo");
                txtDBName.Focus();
                return;
            }
            if (txtUserName.Text.Trim() == "")
            {
                MessageBox.Show("Tên truy cập cơ sở dữ liệu không hợp lệ.", "Cảnh báo");
                txtUserName.Focus();
                return;
            }

            string result = RestoreMySQLDatabase(txtDBName.Text.Trim(),
                txtHelperPath.Text, txtUserName.Text.Trim(),
                txtPassword.Text.Trim(), txtServer.Text.Trim(),
                txtDataPath.Text.Trim());
            if (result != "")
            {
                MessageBox.Show(result, "Cảnh báo");
                return;
            }
            else
            {
                MessageBox.Show("Phục hồi cơ sở dữ liệu thành công.", "Thông báo");
                DialogResult = DialogResult.OK;
            }
        }

        public string RestoreMySQLDatabase(string databasename, string mysqlPath, string username, string password, string host, string inputFile)
        {
            try
            {
                ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe", "/C \"" + mysqlPath + "\" -u " + username + " -h " + host + " --password=" + password + " " + databasename + " < " + inputFile);
                //ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + mysqlPath + " -u " + username + " -h " + host + " -p " + password + " " + databasename + " < " + inputFile);
                pInfo.CreateNoWindow = true;
                pInfo.UseShellExecute = false;
                pInfo.RedirectStandardOutput = true;
                pInfo.RedirectStandardError = true;
                Process process = Process.Start(pInfo);
                string output = process.StandardError.ReadToEnd();

                process.WaitForExit();
                process.Close();
                return output;
            }
            catch (Exception ex)
            {
                return "Lỗi: " + ex.Message;
            }
        }

        public string BackupMySQLDatabase(string databasename, string mysqldumpPath, string username, string password, string host, string outputFile)
        {
            try
            {
                ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe", "/C \"" + mysqldumpPath + "\" -u " + username + " -h " + host + " --password=" + password + " " + databasename + " > " + outputFile);
                //ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + mysqlPath + " -u " + username + " -h " + host + " -p " + password + " " + databasename + " < " + inputFile);
                pInfo.CreateNoWindow = true;
                pInfo.UseShellExecute = false;
                pInfo.RedirectStandardOutput = true;
                pInfo.RedirectStandardError = true;
                Process process = Process.Start(pInfo);
                string output = process.StandardError.ReadToEnd();

                process.WaitForExit();
                process.Close();
                return output;
            }
            catch (Exception ex)
            {
                return "Lỗi: " + ex.Message;
            }
        }

        protected bool ExecuteBatchFile(string batchFileName, string[] argumentsToBatchFile)
        {
            string argumentsString = string.Empty;
            try
            {
                //Add up all arguments as string with space separator between the arguments
                if (argumentsToBatchFile != null)
                {
                    for (int count = 0; count < argumentsToBatchFile.Length; count++)
                    {
                        argumentsString += " ";
                        argumentsString += argumentsToBatchFile[count];
                        //argumentsString += "\"";
                    }
                }

                //Create process start information
                System.Diagnostics.ProcessStartInfo DBProcessStartInfo = new System.Diagnostics.ProcessStartInfo(batchFileName, argumentsString);

                //Redirect the output to standard window
                DBProcessStartInfo.RedirectStandardOutput = true;

                //The output display window need not be falshed onto the front.
                DBProcessStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                DBProcessStartInfo.UseShellExecute = false;

                //Create the process and run it
                System.Diagnostics.Process dbProcess;
                dbProcess = System.Diagnostics.Process.Start(DBProcessStartInfo);

                //Catch the output text from the console so that if error happens, the output text can be logged.
                System.IO.StreamReader standardOutput = dbProcess.StandardOutput;

                /* Wait as long as the DB Backup or Restore or Repair is going on. 
                Ping once in every 2 seconds to check whether process is completed. */
                while (!dbProcess.HasExited)
                    dbProcess.WaitForExit(2000);

                if (dbProcess.HasExited)
                {
                    string consoleOutputText = standardOutput.ReadToEnd();
                    //TODO - log consoleOutputText to the log file.

                }

                return true;
            }

            // Catch all general exceptions
            catch
            {
                return false;
                //ExceptionManager.Publish(ex);
                //throw new CustomizedException(ARCExceptionManager.ErrorCodeConstants.generalError, ex.Message);
            }
        }

        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnFileExec_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Exec files|*.exe";
            dlg.Title = "Chọn file";
            dlg.InitialDirectory = Application.StartupPath;
            if (dlg.ShowDialog() == DialogResult.OK)
                txtHelperPath.Text = dlg.FileName;
        }
    }
}
